import { createStore } from "vuex";
import {CookieUtil} from "@/utils/cookie";
import request from "@/utils/request";
const store = createStore({
    state:{
        token:undefined,
        userInfo:{
            userName:"",
            role:''
        }
    },
    mutations:{
        login(state, {userInfo,token}){
            state.token = token;
            state.userInfo = userInfo;
            CookieUtil.setCookie("token", token);
            localStorage.setItem("userInfo",userInfo);
        },
        logout(state){
            state.token = null;
            state.userInfo = {};
            CookieUtil.deleteCookie("token");
            localStorage.removeItem("userInfo");
        },
        setUserInfo(state, {userInfo}) {
            state.userInfo = userInfo;
            localStorage.setItem("userInfo",userInfo);
        },
    },
    actions:{
        async login({ commit }, { userName, password }) {
            try {
                const response = await request.post('/user/login', { userName, password });
                if (response.code === 200) {
                    commit('login', {userInfo:response.data,token:response.data.token});
                    return Promise.resolve();
                } else {
                    return Promise.reject(new Error(response.message));
                }
            } catch (error) {
                return Promise.reject(new Error('请求出错'));
            }
        },
        async validateToken({ commit }) {
            const token = CookieUtil.getCookies('token');
            if (token) {
                try {
                    const response = await request.get('/user/userInfo', { token });
                    if (response.code === 200) {
                        commit('setUserInfo', {userInfo:response.data});
                        return Promise.resolve();
                    } else {
                        commit('logout');
                        return Promise.reject(new Error(response.message));
                    }
                } catch (error) {
                    commit('logout');
                    return Promise.reject(new Error('请求出错'));
                }
            } else {
                commit('logout');
                return Promise.reject(new Error('Token 不存在,请重新登陆'));
            }
        },
        // eslint-disable-next-line no-unused-vars
        async register({ commit }, { userName, password,role }) {
            try {
                const response = await request.post('/user/register', { userName, password,role  });
                if (response.code === 200) {
                    return Promise.resolve();
                } else {
                    return Promise.reject(new Error(response.message));
                }
            } catch (error) {
                return Promise.reject(new Error('请求出错'));
            }
        }
    }
})
export default store
